<?php

class IndexAction extends Action {

    var $Api;
    var $json;

    public function _initialize() {



        $this->Api = A("Api");

        setcookie('refer', $_SERVER["REQUEST_URI"], time() + 3600);
//setcookie("refer","123");
//setcookie("refer",$_SERVER["REQUEST_URI"],time()+3600);
        $this->json = (isset($_REQUEST['json'])) ? $_REQUEST['json'] : 0;
    }

    public function index() {
        /**
         * 获取当前用户的 UID 和 用户名
         * Cookie 解密直接用 uc_authcode 函数，用户使用自己的函数
         */
        $members[username] = $_SESSION['username'];
        $members[uid] = $_SESSION['uid'];
        //print_r($user);exit();
        if (!empty($members)) {
            $this->assign('Example_username', $members[username]);
            $this->assign('Example_uid', $members[uid]);
        } else {
            $Example_uid = $Example_username = '';
        }

        $list =  M("banner")->select();
        $list=$this->_array_column($list,'member_id');
        $list_keys = array_rand($list,6); 
        foreach ($list_keys as $key => $value) {
            $list_banner[$key]=$list[$value];
        }
        
        $pid = array_rand($list_banner,1);
        $pid_r=$list_banner[$pid];
        
        $map['uid'] = array('IN', $list_banner);
        
        $uids= M("members")->where($map)->select();
        shuffle($uids);
        $this->assign('uids', $uids);
        $this->assign('pid', $pid_r);
        import("@.ORG.Client");

        $i = new Client();
        $j = $i->getDevice();
        //https://www.2345.com/?37297-0001
        // echo $j;
        if ($j == 'pc') {
            $this->display("app");
        } else {




            $this->display("app");
        }
    }

    public function zndex() {
        $this->display();
    }

    public function rand_sort() {
        $map['is_mobile']=1;

        $uids= M("members")->field('uid')->where($map)->select();
        $count=M("members")->field('uid')->where($map)->count();
        $number = range(1,$count);
        shuffle($number);
        $data=array();

        // print_r($uids);
        foreach ($uids as $key=>$value) {
              array_push($data, array('uid'=>$value['uid'],'sort'=>$number[$key]));
        }
         print_r($data);
        // $data[] = array('uid'=>1,'sort'=>1);
        // $data[] = array('uid'=>2,'sort'=>2);
        // $data[] = array('uid'=>3,'sort'=>3);
        $this->saveAll($data,'z_members');
      
      
    }

    public function remove_one() {

        $map['is_mobile']=1;
        $map['review']=2;
        $list= M("members")->field('uid')->where($map)->select();
        $list=$this->_array_column($list,'uid');
        // print_r($list);
        // print_r(array_rand($list,1));

        $key=array_rand($list,1);

        $uid=$list[$key];

        $data = array(
            'review' => 3,
        );

        $map_uid['uid']=$uid;

        $res = M('members')->where($map_uid)->save($data);



        
    }

    public function add_one() {

        $map['is_mobile']=1;
        $map['review']=3;
        $list= M("members")->field('uid')->where($map)->select();
        $list=$this->_array_column($list,'uid');
        // print_r($list);
        // print_r(array_rand($list,1));

        $key=array_rand($list,1);

        $uid=$list[$key];

        $data = array(
            'review' => 2,
        );

        $map_uid['uid']=$uid;

        $res = M('members')->where($map_uid)->save($data);



        
    }

    public function saveAll($datas,$model){
        $model || $model=$this->name;
        $sql   = ''; //Sql
        $lists = []; //记录集$lists
        $pk    ="uid";//获取主键
        foreach ($datas as $data) {
            foreach ($data as $key=>$value) {
                if($pk===$key){
                    $ids[]=$value;
                }else{
                    $lists[$key].= sprintf("WHEN %u THEN '%s' ",$data[$pk],$value);
                }
            }
        }
        foreach ($lists as $key => $value) {
            $sql.= sprintf("`%s` = CASE `%s` %s END,",$key,$pk,$value);
        }
        $sql = sprintf('UPDATE %s SET %s WHERE %s IN ( %s )',strtoupper($model),rtrim($sql,','),$pk,implode(',',$ids));
        $sql=strtolower($sql);
        print_r($sql);

        return M()->execute($sql);
    }
    
     public function banner() {
        $list =  M("banner")->select();
        $list=$this->_array_column($list,'member_id');
        $list_keys = array_rand($list,2); 
        foreach ($list_keys as $key => $value) {
            $list_banner[$key]=$list[$value];
        }
        
        $pid = array_rand($list_banner,1);
        $pid_r=$list_banner[$pid];
        
        $map['uid'] = array('IN', $list_banner);
        
        $uids= M("members")->field('banner,ad')->where($map)->select();
        shuffle($uids);

        foreach ($uids as $key => $value) {
        $kros_key="woqumima";
        $uids[$key]['banner']=$this->cryptoJsAesEncrypt($kros_key,$value['banner']);
        $uids[$key]['ad']=$this->cryptoJsAesEncrypt($kros_key,$value['ad']);
        }
        echo json_encode($uids);
    }

    public function gallery() {
        $this->display();
    }

    public function about() {
        $this->display();
    }

    public function features() {
        $this->display();
    }

    public function typography() {
        $this->display();
    }

    public function contact() {
        $this->display();
    }

    public function ajax_getvideo() {
        $kros = M("v1");
        $list = $kros->order('id desc')->findAll();
        if ($list) {
            // 成功后返回客户端新增的用户ID，并返回提示信息和操作状态
            $kajx = $this->ajaxReturn($list);
            //$this->assign('kajx',$kajx);
        } else {
            // 错误后返回错误的操作状态和提示信息
            $this->ajaxReturn(0, "新增错误！", 0);
        }
    }

    public function think_send_mail($to, $name, $subject = '', $body = '', $attachment = null) {
        $config = C('THINK_EMAIL');
        Vendor('PHPMailer.classphpmailer');
        //import("@.ORG.Phpmailer"); //从PHPMailer目录导class.phpmailer.php类文件
        $mail = new PHPMailer(); //PHPMailer对象
        $mail->CharSet = 'UTF-8'; //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
        $mail->IsSMTP(); // 设定使用SMTP服务
        $mail->SMTPDebug = 0; // 关闭SMTP调试功能
        // 1 = errors and messages
        // 2 = messages only
        $mail->SMTPAuth = true; // 启用 SMTP 验证功能
        $mail->SMTPSecure = 'ssl'; // 使用安全协议
        $mail->Host = $config['SMTP_HOST']; // SMTP 服务器
        $mail->Port = $config['SMTP_PORT']; // SMTP服务器的端口号
        $mail->Username = $config['SMTP_USER']; // SMTP服务器用户名
        $mail->Password = $config['SMTP_PASS']; // SMTP服务器密码
        $mail->SetFrom($config['FROM_EMAIL'], $config['FROM_NAME']);
        $replyEmail = $config['REPLY_EMAIL'] ? $config['REPLY_EMAIL'] : $config['FROM_EMAIL'];
        $replyName = $config['REPLY_NAME'] ? $config['REPLY_NAME'] : $config['FROM_NAME'];
        $mail->AddReplyTo($replyEmail, $replyName);
        $mail->Subject = $subject;
        $mail->MsgHTML($body);
        $mail->AddAddress($to, $name);
        if (is_array($attachment)) { // 添加附件
            foreach ($attachment as $file) {
                is_file($file) && $mail->AddAttachment($file);
            }
        }
        return $mail->Send() ? true : $mail->ErrorInfo;
    }

    public function send_mail($frommail, $tomail, $subject, $body, $ccmail, $bccmail) {
        //import("@.ORG.P8_smtp");
        Vendor('PHPMailer.classphpmailer');
        $mail = new PHPMailer();
        $mail->IsSMTP(); // 经smtp发送
        $mail->Host = "smtp.qq.com"; // SMTP 服务器
        $mail->Port = '25';
        $mail->SMTPAuth = true; // 打开SMTP 认证
        $mail->Username = "315902734@qq.com"; // 用户名
        $mail->Password = "Cjg13241064679"; // 密码
        $mail->From = $frommail; // 发信人
        $mail->FromName = "suport of 51yip"; // 发信人别名
        $mail->AddAddress($tomail); // 收信人
        if (!empty($ccmail)) {
            $mail->AddCC($ccmail); // cc收信人
        }
        if (!empty($bccmail)) {
            $mail->AddCC($bccmail); // bcc收信人
        }
        $mail->WordWrap = 50;
        $mail->IsHTML(true); // 以html方式发送
        $mail->Subject = $subject; // 邮件标题
        $mail->Body = $body; // 邮件内空
        $mail->AltBody = "请使用HTML方式查看邮件。";
        return $mail->Send();
    }

    public function kros_t() {
        echo "dfdf";
    }

    public function mail() {
        //$result=$this->think_send_mail("315902734@163.com","sdfdf","sdfsdfsdf","sdfsdfdf");
        echo "string";
        //$this->kros_t();
        $result = $this->send_mail("315902734@qq.com", "315902734@163.com", "test", "test");
        echo "string1";
        /*
          $mail = new Phpmailer();



          $mail->FromName = "peterlee";
          $mail->AddAddress($address, "");//收件人地址，可以替换成任何想要接收邮件的email信箱,格式是AddAddress("收件人email","收件人姓名")
          //$mail->AddReplyTo("", "");

          //$mail->AddAttachment("/var/tmp/file.tar.gz"); // 添加附件
          //$mail->IsHTML(true); // set email format to HTML //是否使用HTML格式

          $mail->Subject = "验证邮件"; //邮件标题
          $mail->Body = "Hello,这是测试邮件"; //邮件内容
          $mail->AltBody = "This is the body in plain text for non-HTML mail clients"; //附加信息，可以省略

          $mail->Send();
          $mail = new PHPMailer(); //建立邮件发送类
          $address = "315902734@163.com";
          $mail->IsSMTP(); // 使用SMTP方式发送
          $mail->Host = "smtp.qq.com"; // 您的企业邮局域名
          $mail->SMTPAuth = true; // 启用SMTP验证功能
          $mail->Username = "315902734@qq.com"; // 邮局用户名(请填写完整的email地址)
          $mail->Password = "Cjg13241064679"; // 邮局密码

          $mail->From = "315902734@qq.com"; //邮件发送者email地址 */
    }

    public function kros_m() {
        //import("@.ORG.Smtp");

        /**
         * 服务器信息
         */
        $MailServer = 'smtp.qq.com'; //SMTP 服务器
        $MailPort = '25'; //SMTP服务器端口号 默认25
        $MailId = '315902734@qq.com'; //服务器帐号
        $MailPw = 'Cjg13241064679'; //服务器账号密码

        /**
         * 客户端信息
         */
        $Title = '测试邮件标题'; //邮件标题
        $Content = '测试邮件内容'; //邮件内容
        $email = '223.com'; //接收者邮箱
        $smtp = new smtp($MailServer, $MailPort, true, $MailId, $MailPw);
        $smtp->debug = true; //实例化类
        if ($smtp->sendmail($email, $MailId, $Title, $Content, "HTML")) {
            echo '邮件发送成功'; //返回结果
        } else {
            echo '邮件发送失败'; //$succeed = 0;
        }
        //$smtp->sendmail($email,$MailId, $Title, $Content, "HTML") //发送邮件
        /* $result= $this->send_mail("315902734@qq.com","315902734@163.com","test","test");
          //$result=$this->think_send_mail("315902734@163.com","sdfdf","sdfsdfsdf","sdfsdfdf",null); */
        echo "string";
    }

    public function houge() {
        $members[username] = $_SESSION['username'];
        $members[uid] = $_SESSION['uid'];
        if (!empty($members)) {
            $this->assign('Example_username', $members[username]);
            $this->assign('Example_uid', $members[uid]);
        } else {
            $Example_uid = $Example_username = '';
        }
        $kros = M("v1"); // 实例化模型类
        $list = $kros->where("tag='吼歌'")->order('id desc')->select(); // 创建数据对象
        $this->assign('list', $list);
        $this->display('index');
    }

    public function qiangge() {
        $members[username] = $_SESSION['username'];
        $members[uid] = $_SESSION['uid'];
        if (!empty($members)) {
            $this->assign('Example_username', $members[username]);
            $this->assign('Example_uid', $members[uid]);
        } else {
            $Example_uid = $Example_username = '';
        }
        $kros = M("v1"); // 实例化模型类
        $list = $kros->where("tag='强哥说事'")->order('id desc')->select(); // 创建数据对象
        $this->assign('list', $list);
        $this->display('index');
    }

    public function daren() {
        $members[username] = $_SESSION['username'];
        $members[uid] = $_SESSION['uid'];
        if (!empty($members)) {
            $this->assign('Example_username', $members[username]);
            $this->assign('Example_uid', $members[uid]);
        } else {
            $Example_uid = $Example_username = '';
        }
        $kros = M("v1"); // 实例化模型类
        $list = $kros->where("tag='达人秀'")->order('id desc')->select(); // 创建数据对象
        $this->assign('list', $list);
        $this->display('index');
    }

    public function paike() {
        $members[username] = $_SESSION['username'];
        $members[uid] = $_SESSION['uid'];
        if (!empty($members)) {
            $this->assign('Example_username', $members[username]);
            $this->assign('Example_uid', $members[uid]);
        } else {
            $Example_uid = $Example_username = '';
        }
        $kros = M("v1"); // 实例化模型类
        $list = $kros->where("tag='拍客'")->order('id desc')->select(); // 创建数据对象
        $this->assign('list', $list);
        $this->display('index');
    }

    public function pingce() {
        $members[username] = $_SESSION['username'];
        $members[uid] = $_SESSION['uid'];
        if (!empty($members)) {
            $this->assign('Example_username', $members[username]);
            $this->assign('Example_uid', $members[uid]);
        } else {
            $Example_uid = $Example_username = '';
        }
        $kros = M("v1"); // 实例化模型类
        $list = $kros->where("tag='手机评测'")->order('id desc')->select(); // 创建数据对象
        $this->assign('list', $list);
        $this->display('index');
    }

    public function tucao() {
        $members[username] = $_SESSION['username'];
        $members[uid] = $_SESSION['uid'];
        if (!empty($members)) {
            $this->assign('Example_username', $members[username]);
            $this->assign('Example_uid', $members[uid]);
        } else {
            $Example_uid = $Example_username = '';
        }
        $kros = M("v1"); // 实例化模型类
        $list = $kros->where("tag='吐槽'")->order('id desc')->select(); // 创建数据对象
        $this->assign('list', $list);
        $this->display('index');
    }

    public function dalei() {
        $members[username] = $_SESSION['username'];
        $members[uid] = $_SESSION['uid'];
        if (!empty($members)) {
            $this->assign('Example_username', $members[username]);
            $this->assign('Example_uid', $members[uid]);
        } else {
            $Example_uid = $Example_username = '';
        }
        $kros = M("v1"); // 实例化模型类
        $list = $kros->where("tag='打擂'")->order('id desc')->select(); // 创建数据对象
        $this->assign('list', $list);
        $this->display('index');
    }

    public function showtime() {
        $members[username] = $_SESSION['username'];
        $members[uid] = $_SESSION['uid'];
        if (!empty($members)) {
            $this->assign('Example_username', $members[username]);
            $this->assign('Example_uid', $members[uid]);
        } else {
            $Example_uid = $Example_username = '';
        }
        $kros = M("v1"); // 实例化模型类
        $list = $kros->where("tag='SHOWTIME'")->order('id desc')->select(); // 创建数据对象
        $this->assign('list', $list);
        $this->display('index');
    }

    public function PIPHP_MakeThumbnail($image, $max) {
        // Plug-in 13: Make Thumbnail
        //
        // This plug-in takes a GD image and returns a copy as
        // a thumbnail. The arguments required are:
        //
        //    $image: The image source
        //    $max:   Maximum width and height
        $thumbw = $w = imagesx($image);
        $thumbh = $h = imagesy($image);
        if ($w > $h && $max < $w) {
            $thumbh = $max / $w * $h;
            $thumbw = $max;
        } elseif ($h > $w && $max < $h) {
            $thumbw = $max / $h * $w;
            $thumbh = $max;
        } elseif ($max < $w) {
            $thumbw = $thumbh = $max;
        }
        return PIPHP_ImageResize($image, $thumbw, $thumbh);
    }

    // The function below is repeated here
    // just for the sake of this example as it
    // is called by it.
    public function PIPHP_ImageResize($image, $w, $h) {
        // Plug-in 12: Image Resize
        // This plug-in takes a GD image and resizes it to the
        // required dimensions. The arguments are:
        //    $image: The image source
        //    $w:     New width
        //    $h:     New height
        $oldw = imagesx($image);
        $oldh = imagesy($image);
        $temp = imagecreatetruecolor($w, $h);
        imagecopyresampled($temp, $image, 0, 0, 0, 0, $w, $h, $oldw, $oldh);
        return $temp;
    }

    public function sheng() {
        import("@.ORG.Resizeimage");
        $save_path = 'Public/';
        $file_name = 'test.jpg';
        $resizeimage = new Resizeimage($save_path . $file_name, "185", "130", "0", $save_path . "c_" . $file_name);
    }

    public function upload() {
        if (!empty($_FILES)) {
            //如果有文件上传 上传附件
            $this->_upload();
            //$this->forward();
        }
    }

    // 文件上传
    protected function _upload() {
        import("@.ORG.UploadFile");
        $upload = new UploadFile();
        //设置上传文件大小
        $upload->maxSize = 3292200;
        //设置上传文件类型
        $upload->allowExts = explode(',', 'jpg,gif,png,jpeg');
        //设置附件上传目录
        $upload->savePath = 'Public/Uploads/';
        //设置需要生成缩略图，仅对图像文件有效
        $upload->thumb = true;
        //设置需要生成缩略图的文件后缀
        $upload->thumbPrefix = 'm_,s_'; //生产2张缩略图
        //设置缩略图最大宽度
        $upload->thumbMaxWidth = '120,60';
        //设置缩略图最大高度
        $upload->thumbMaxHeight = '140,60';
        //设置上传文件规则
        $upload->saveRule = uniqid;
        //删除原图
        $upload->thumbRemoveOrigin = true;
        if (!$upload->upload()) {
            //捕获上传异常
            $kros_err = $upload->getErrorMsg();
            echo $kros_err;
            $this->redirect('index/kroserv3', array(), 5, ' 发布失败!,5秒钟后页面跳转中 ~');
        } else {
            //取得成功上传的文件信息
            $uploadList = $upload->getUploadFileInfo();
            $_POST['image'] = $uploadList[0]['savename'];
            $model = M('gequ');
            //保存当前数据对象
            $data['image'] = $_POST['image'];
            $data['create_time'] = time();
            $list = $model->add($data);
            if ($list !== false) {
                // $this->success ('上传图片成功！');
                $this->redirect('index', array(), 5, ' 发布成功!,5秒钟后页面跳转中 ~');
            } else {
                //$this->error ('上传图片失败!');
                $this->redirect('index/kroserv3', array(), 5, ' 发布失败!,5秒钟后页面跳转中 ~');
            }
        }
    }

    public function ding() {
        import("@.ORG.Json");
        $kros = M("gequ"); // 实例化User对象
        //$data['ding'] = $data['ding'] +1;
        //使用setInt 增加积分
        $kros->setInc('ding', 'id=' . $_REQUEST['id'], 1);
        //$kros->where('id='.$_REQUEST['id'])->save($data); // 根据条件保存修改的数据
        $list = $kros->where('id=' . $_REQUEST['id'])->find();
        echo json_encode($list);
    }

    public function cai() {
        $kros = M("gequ"); // 实例化User对象
        //$data['ding'] = $data['ding'] +1;
        //使用setInt 增加积分
        $kros->setInc('cai', 'id=' . $_REQUEST['id'], 1);
        $list = $kros->where('id=' . $_REQUEST['id'])->find();
        echo json_encode($list);
    }

    public function piax_upload() {
        //echo $_POST['video'];
        //echo $_POST['tag'];
        // echo  $this->get_extension($_POST['img']);
        /* if (($this->get_extension($_POST['img'])=='jpg')||($this->get_extension($_POST['img'])=='gif')||($this->get_extension($_POST['img'])=='png')) {
          echo "1";
          } else {
          echo "封面图片类型不允许";
          } */
        if (!empty($_COOKIE['Example_auth'])) {
            list($Example_uid, $Example_username) = explode("\t", uc_authcode($_COOKIE['Example_auth'], 'DECODE'));
            $kros_shuzu = array(
                "jpg",
                "jpeg",
                "gif",
                "png",
                "JPG",
                "GIF",
                "PNG"
            );
            $kros_cunzai = $this->get_extension($_POST['img']);
            if (in_array($kros_cunzai, $kros_shuzu) == false) {
                echo "封面图片类型不允许";
                $this->redirect('index/kroserv3', array(), 5, ' 5秒钟后页面跳转中 ~');
            }
            $kros_shuzu1 = array(
                "mp4",
                "flv",
                "3gp",
                "MP4",
                "FLV"
            );
            $kros_video = trim($_POST['video']);
            if (substr($kros_video, 1, 3) != "ttp") {
                $kros_cunzai1 = $this->get_extension($kros_video);
                if (in_array($kros_cunzai1, $kros_shuzu1) == false) {
                    echo "视频类型不允许";
                    $this->redirect('index/kroserv3', array(), 5, ' 5秒钟后页面跳转中 ~');
                }
            }
            if ((in_array($kros_cunzai, $kros_shuzu) && in_array($kros_cunzai1, $kros_shuzu1)) || (in_array($kros_cunzai, $kros_shuzu) && substr($kros_video, 1, 3) == "ttp")) {
                $kros = M("gequ");
                $data['geming'] = $_POST['video_name'];
                $data['image'] = $_POST['img'];
                $data['video'] = $_POST['video'];
                $data['jieshao'] = $_POST['video_jieshao'];
                $data['tag'] = $_POST['tag'];
                $data['create_time'] = time();
                $data['uid'] = $Example_uid;
                $kros->add($data);
                $MailServer = 'smtp.qq.com'; //SMTP 服务器
                $MailPort = '25'; //SMTP服务器端口号 默认25
                $MailId = '315902734@qq.com'; //服务器帐号
                $MailPw = 'Cjg13241064679'; //服务器账号密码

                /**
                 * 客户端信息
                 */
                //header("content-type:text/html;charset=utf-8");
                $Title = "=?UTF-8?B?" . base64_encode($_POST['video_name']) . "?="; //邮件标题
                $Content = iconv("UTF-8", "GB2312//IGNORE", $_POST['video_name']); //邮件内容
                $email = '315902734@163.com'; //接收者邮箱
                $smtp = new smtp($MailServer, $MailPort, true, $MailId, $MailPw);
                $smtp->debug = true; //实例化类
                if ($smtp->sendmail($email, $MailId, $Title, $Content, 6)) {
                    // echo '邮件发送成功';            //返回结果
                } else {
                    echo '邮件发送失败'; //$succeed = 0;
                }
                echo "上传成功!";
                $this->redirect('index/', array(), 5, ' 5秒钟后页面跳转中 ~');
            }
        } else {
            $Example_uid = $Example_username = '';
            echo "Please Login First!";
            $this->redirect('index/kroserv3', array(), 5, ' 5秒钟后页面跳转中 ~');
        }
    }

    //获取文件扩展名
    public function get_extension($file) {
        return pathinfo($file, PATHINFO_EXTENSION);
    }

    public function kros_upload2() {
        /*  $kros_folder = '/kros/Public/Uploads/';
          mkdir($_SERVER['DOCUMENT_ROOT'] . kros_folder.date("Ymd"), 0700); */
        if (!empty($_POST['denglu'])) {
            $targetFolder = '/kros/Public/Uploads/' . date("Ymd"); // Relative to the root
            if (!file_exists('Public/Uploads/' . date("Ymd"))) {
                mkdir('Public/Uploads/' . date("Ymd"), 0777);
            }
            $verifyToken = md5('unique_salt' . $_POST['timestamp']);
            if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
                $tempFile = $_FILES['Filedata']['tmp_name'];
                $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
                $_FILES['Filedata']['name'] = iconv('utf-8', 'gb2312', $_FILES['Filedata']['name']);
                $targetFile = rtrim($targetPath, '/') . '/' . $_FILES['Filedata']['name'];
                // Validate the file type
                $fileTypes = array(
                    'jpg',
                    'gif',
                    'png',
                    'jpeg',
                    'JPG',
                    'GIF',
                    'PNG'
                ); // File extensions
                $fileParts = pathinfo($_FILES['Filedata']['name']);
                if (in_array($fileParts['extension'], $fileTypes)) {
                    move_uploaded_file($tempFile, $targetFile);
                    //生成缩略图
                    import("@.ORG.Resizeimage");
                    $save_path = rtrim($targetPath, '/') . '/';
                    $file_name = $_FILES['Filedata']['name'];
                    $resizeimage = new Resizeimage($save_path . $file_name, "237", "247", "0", $save_path . "c_" . $file_name);
                    $resizeimage1 = new Resizeimage($save_path . $file_name, "640", "264", "0", $save_path . "c1_" . $file_name);
                    //生成缩略图
                    echo $targetFolder;
                    /* addcode */
                    setcookie("cookie[one]", "cookieone");
                    /* addcode */
                } else {
                    echo 'Invalid file type.';
                }
            }
        }
    }

    public function kros_upload1() {
        if (!empty($_POST['denglu'])) {
            $targetFolder = '/kros/Public/Uploads/' . date("Ymd"); // Relative to the root
            if (!file_exists('Public/Uploads/' . date("Ymd"))) {
                mkdir('Public/Uploads/' . date("Ymd"), 0777);
            }
            $verifyToken = md5('unique_salt' . $_POST['timestamp']);
            if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
                $tempFile = $_FILES['Filedata']['tmp_name'];
                $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
                $_FILES['Filedata']['name'] = iconv('utf-8', 'gb2312', $_FILES['Filedata']['name']);
                $targetFile = rtrim($targetPath, '/') . '/' . $_FILES['Filedata']['name'];
                // Validate the file type
                $fileTypes = array(
                    'mp4',
                    '3gp',
                    'flv',
                    'avi'
                ); // File extensions
                $fileParts = pathinfo($_FILES['Filedata']['name']);
                if (in_array($fileParts['extension'], $fileTypes)) {
                    move_uploaded_file($tempFile, $targetFile);
                    echo '1';
                    /* addcode */
                    setcookie("cookie[one]", "cookieone");
                    /* addcode */
                } else {
                    echo 'Invalid file type.';
                }
            }
        }
    }

    public function kros_upload() {
        $error = "";
        $msg = "";
        $fileElementName = 'Filedata';
        if (!empty($_FILES[$fileElementName]['error'])) {
            switch ($_FILES[$fileElementName]['error']) {
                case '1':
                    $error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
                    break;

                case '2':
                    $error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
                    break;

                case '3':
                    $error = 'The uploaded file was only partially uploaded';
                    break;

                case '4':
                    $error = 'No file was uploaded.';
                    break;

                case '6':
                    $error = 'Missing a temporary folder';
                    break;

                case '7':
                    $error = 'Failed to write file to disk';
                    break;

                case '8':
                    $error = 'File upload stopped by extension';
                    break;

                case '999':
                default:
                    $error = 'No error code avaiable';
            }
        } elseif (empty($_FILES['Filedata']['tmp_name']) || $_FILES['Filedata']['tmp_name'] == 'none') {
            $error = 'No file was uploaded..';
        } else {
            $msg .= " File Name: " . $_FILES['Filedata']['name'] . ", ";
            $msg .= " File Size: " . @filesize($_FILES['Filedata']['tmp_name']);
            //for security reason, we force to remove all uploaded file
            /* addcode */
            $msg = "涓婁紶鎴愬姛!";
            move_uploaded_file($_FILES["Filedata"]["tmp_name"], "Public/Uploads/" . $_FILES["Filedata"]["name"]);
            /* addcode */
            @unlink($_FILES['Filedata']);
        }
        echo "{";
        echo "error: '" . $error . "',\n";
        echo "msg: '" . $msg . "'\n";
        echo "}";
    }

    public function logout() {
        setcookie('Example_auth', '', -86400);
        //生成同步退出的代码
        $ucsynlogout = uc_user_synlogout();
        $this->redirect('index', array(), 5, ' 安全退出!,5秒钟后页面跳转中 ~');
    }

    public function show() {
        $id = $_REQUEST['id'];
        $kros = M("v1");
        $condition['id'] = $id;
        $video = $kros->where($condition)->find();
        //var_dump($video['bigimg']);
        $this->assign('video', $video);
        /* if (substr($video['video'], -4,1)==".") {
          $this->display("show");
          } else {
          $this->display("showp");
          }
         */
        if ((substr($video['video'], -3) == "mp4") || (substr($video['video'], -3) == "flv") || (substr($video['video'], -3) == "3gp")) {
            $this->display("show");
        } else {
            $this->display("showp");
        }
    }

    public function changetou() {
        $kros = uc_avatar(2, real, 1);
        echo $kros;
    }

    public function kroserv3() {
        if (!empty($_COOKIE['Example_auth'])) {
            list($Example_uid, $Example_username) = explode("\t", uc_authcode($_COOKIE['Example_auth'], 'DECODE'));
            //var_dump($Example_username);
            $this->assign('Example_username', $Example_username);
            $this->assign('Example_uid', $Example_uid);
        } else {
            $Example_uid = $Example_username = '';
        }
        $this->display("kroserv3");
    }

    public function kroserv5() {
        if (!empty($_COOKIE['Example_auth'])) {
            list($Example_uid, $Example_username) = explode("\t", uc_authcode($_COOKIE['Example_auth'], 'DECODE'));
            //var_dump($Example_username);
            $this->assign('Example_username', $Example_username);
            $this->assign('Example_uid', $Example_uid);
        } else {
            $Example_uid = $Example_username = '';
        }
        $this->display("kroserv5");
    }

    public function login() {
        $this->display("login");
    }

    public function reg() {
        $this->display("reg");
    }

    public function reg_act() {
        $uid = uc_user_register($_POST['username'], $_POST['password'], $_POST['email']);
        if ($uid <= 0) {
            if ($uid == - 1) {
                $this->redirect('index/reg', array(), 5, ' 用户名不合法,5秒钟后页面跳转中 ~');
            } elseif ($uid == - 2) {
                $this->redirect('index/reg', array(), 5, ' 包含要允许注册的词语,5秒钟后页面跳转中 ~');
            } elseif ($uid == - 3) {
                $this->redirect('index/reg', array(), 5, ' 用户名已经存在,5秒钟后页面跳转中 ~');
            } elseif ($uid == - 4) {
                $this->redirect('index/reg', array(), 5, ' Email 格式有误,5秒钟后页面跳转中 ~');
            } elseif ($uid == - 5) {
                $this->redirect('index/reg', array(), 5, ' Email 不允许注册,5秒钟后页面跳转中 ~');
            } elseif ($uid == - 6) {
                $this->redirect('index/reg', array(), 5, ' Email 已被注册,5秒钟后页面跳转中 ~');
            } else {
                $this->redirect('index/reg', array(), 5, ' 未定义,5秒钟后页面跳转中 ~');
            }
        } else {
            setcookie('Example_auth', uc_authcode($uid . "\t" . $username, 'ENCODE'));
            /*    echo '注册成功'; */
            $this->redirect('index/index', array(), 5, ' 注册成功,5秒钟后页面跳转中 ~');
        }
    }

    public function check() {
        list($uid, $username, $password, $email) = uc_user_login($_POST['username'], $_POST['password']);
        setcookie('Example_auth', '', -86400);
        if ($uid > 0) {
            setcookie('Example_auth', uc_authcode($uid . "\t" . $username, 'ENCODE'));
            $ucsynlogin = uc_user_synlogin($uid);
            //$this->success(" 登录成功！ " );
            $this->redirect('index', array(), 5, ' 登录成功!,5秒钟后页面跳转中 ~');
            // echo '登录成功'.$ucsynlogin.'<br><a href="'.$_SERVER['PHP_SELF'].'">继续</a>';
            exit;
        } elseif ($uid == - 1) {
            echo '用户不存在,或者被删除';
            $this->redirect('index/login', array(), 5, ' 5秒钟后页面跳转中 ~');
        } elseif ($uid == - 2) {
            echo '密码错';
            $this->redirect('index/login', array(), 5, ' 5秒钟后页面跳转中 ~');
        } else {
            echo '未定义';
            $this->redirect('index/login', array(), 5, ' 5秒钟后页面跳转中 ~');
        }
        if ($data = uc_get_user($username)) {
            list($uid, $username, $email) = $data;
        } else {
            echo '用户不存在';
        }
        //var_dump($username);
    }

    public function ajax() {
        // var_dump($_POST);die;
        $data = array();
        $kros = M("msg");
        //$Model = new Model();
        $data['content'] = $_POST['content'];
        $data['time'] = time();
        $data['timee'] = date('Y-m-d H:i:s', time());
        // $data['sender']=session('account');
        // var_dump($data);die;
        $dd = $kros->add($data);
        //$dd=M(msg)->data($data)->add();
        //   $dataa=M(msg)->order('id desc')->limit('5')->select();
        $list = $kros->order('id desc')->limit('5')->select();
        $this->ajaxReturn($list);
    }

    /**
     * 刷新时获取最新五条聊天内容和在线用户
     */
    public function homePage() {
        $this->msg = M(msg)->order('id desc')->limit('5')->select();
        $this->user = M(user)->where(array(
                    'status' => 1
                ))->select();
        $this->display();
    }

    /**
     * 即时返回最新五条聊天内容
     */
    public function fresh() {
        $kros = M("msg");
        $list = $kros->order('id desc')->limit('5')->select();
        // $data=M(msg)->order('id desc')->limit('5')->select();
        $this->ajaxReturn($list);
    }

    /**
     * 即时返回在线用户
     */
    public function freshUser() {
        $dat = M(user)->where(array(
                    'status' => 1
                ))->select();
        $this->ajaxReturn($dat);
    }

    public function a() {
        $this->display();
    }

    public function live() {
        $this->display();
    }

    public function tuisong() {
        $this->display();
    }

    public function rt() {
        $this->display();
    }

    public function tui1() {
        set_time_limit(0);
        $pid = $_POST['pid'];
        $stream = $_POST['stream'];
        $kros = M("promition");
        $condition['pid'] = $pid;
        $flv = $kros->where($condition)->order('id')->select();
        //  var_dump($flv);
        for ($i = 0; $i < 100; $i++) {
            foreach ($flv as $val) {
                //var_dump($val['flv']);
                $u = trim($val['flv']);
                $pics = explode('.', $u);
                $num = count($pics);
                //echo '<br>'.$pics[$num-1];
                if ($pics[$num - 1] == 'rmvb') {
                    $cmd = 'c:/ffmpeg/bin/ffmpeg.exe  -re -i ' . '"' . $u . '"' . '  -i "d:/kk.png" -filter_complex "overlay=5:5" -qscale 0  -ar 22050 -vcodec h264 -s 640*360 -b 200k  -f flv -y "rtmp://115.28.161.7/live/' . $stream . '"';
                } elseif ($pics[$num - 1] == 'wmv') {
                    $cmd = 'c:/ffmpeg/bin/ffmpeg.exe  -re  -i ' . '"' . $u . '"' . ' -i "d:/kk.png" -filter_complex "overlay=5:5" -q:v 0   -vcodec h264 -s 640*360 -b 200k -f  flv -y "rtmp://115.28.161.7/live/' . $stream . '"';
                } elseif ($pics[$num - 1] == 'flv') {
                    $cmd = 'c:/ffmpeg/bin/ffmpeg.exe  -re  -i ' . '"' . $u . '"' . ' -vcodec copy -acodec   copy -f  flv -y "rtmp://115.28.161.7/live/' . $stream . '"';
                } else {
                    // $cmd = 'c:/ffmpeg/bin/ffmpeg.exe   -i '.'"'.$u.'"'.' -i "d:/kk.jpg" -filter_complex "overlay=5:5" -f flv "rtmp://send1.douyutv.com/live/'.$stream.'"';
                    //$cmd = 'c:/ffmpeg/bin/ffmpeg.exe   -i '.'"'.$u.'"'.' -vf drawtext="fontfile=arial.ttf:text=\'kktv,Give me some fishboll please\':x=00:fontcolor=white:fontsize=16" -f flv "rtmp://send1.douyutv.com/live/'.$stream.'"';
                    //youku
                    //$cmd = 'c:/ffmpeg/bin/ffmpeg.exe  -re  -i '.'"'.$u.'"'.' -i "d:/kk.png" -filter_complex "overlay=5:5" -q:v 0   -vcodec h264 -s 640*360 -b 200k -f  flv -y "rtmp://send1.douyutv.com/live/'.$stream.'"';
                    //
                    /* $cmd = 'c:/ffmpeg/bin/ffmpeg.exe  -re  -i '.'"'.$u.'"'.' -i "d:/kk.png" -filter_complex "overlay=5:5" -q:v 0   -vcodec h264 -s 640*360 -b 200k -f  flv -y "rtmp://115.28.161.7/live/'.$stream.'"'; */
                    $cmd = 'c:/ffmpeg/bin/ffmpeg.exe  -re  -i ' . '"' . $u . '"' . ' -vcodec copy -acodec   copy -f  flv -y "rtmp://115.28.161.7/live/' . $stream . '"';
                }
                //echo $cmd ;
                //$cmd = 'c:/ffmpeg/bin/ffmpeg.exe  -re -i '.'"'.$u.'"'.' -vcodec libx264 -vb 800k  -ab 64k -f flv "rtmp://send1.douyutv.com/live/169124rKJ63kUiiU?wsSecret=110f83d1965eafa24d9b96bfa5d645b8&wsTime=55892b4f"';
                //$cmd = 'c:/ffmpeg/bin/ffmpeg.exe   -i "d:/hdlw.flv" -i "d:/kk.png" -filter_complex "overlay=5:5" -f flv "rtmp://send1.douyutv.com/live/169124rcm4hGiUgX?wsSecret=36a31c3db10941af1c40fe9fac60ca12&wsTime=558ac9ea"';
                //$cmd = 'c:/ffmpeg/bin/ffmpeg.exe  -re -i '.'"'.$u.'"'.' -vcodec copy -acodec   copy -f flv -y "rtmp://send1.douyutv.com/live/169124rcm4hGiUgX?wsSecret=36a31c3db10941af1c40fe9fac60ca12&wsTime=558ac9ea"';
                exec($cmd);
            }
        }
    }

    public function tui() {
        $descriptorspec = array(
            0 => array(
                "pipe",
                "r"
            ), // stdin is a pipe that the child will read from
            1 => array(
                "pipe",
                "w"
            ), // stdout is a pipe that the child will write to
            2 => array(
                "pipe",
                "w"
            ) // stderr is a pipe that the child will write to
        );
        C('URL_MODEL', '0');
        $u = $_POST['u'];
        //$u="http://kwflvcdn.000dn.com/swfs/f8/2469824647cqb/gfd8fgd.flv";
        $cmd = "c:/ffmpeg/bin/ffmpeg.exe  -re -i " . $u . " -vcodec copy -acodec   copy -f flv -y rtmp://115.28.161.7/live/livestream";
        //$cmd="c:\\WINDOWS\\system32\\notepad.exe";
        //
        //exec("c:/ffmpeg/bin/ffmpeg.exe  -re -i c:/ffmpeg/bin/sample.flv  -vcodec copy -acodec   copy -f flv -y rtmp://115.28.161.7/live/livestream",$return_array);
        //exec("c:/ffmpeg/bin/ffmpeg.exe -i  c:/ffmpeg/bin/sample.flv  c:/ffmpeg/bin/sample3.flv",$return_array);
        exec($cmd, $output, $result);
        // var_dump($return_array);
        //exec($cmd,$output,$result);
        //exec("f:/www/ffmpeg.exe -i  f:/www/test.wmv  f:/www/test2.flv");
        /*   $cmd = 'FFMPEG  -i  uploadfile/video/test.wmv -c:v libx264 -strict -2 uploadfile/mp4/test.mp4';
          exec($cmd, $status);
          echo $status; */
        /*
          $process = proc_open($cmd, $descriptorspec, $pipes);


          if (is_resource($process)) {
          $stdin = stream_get_contents($pipes[0]);
          $stdout = stream_get_contents($pipes[1]);
          $stderr = stream_get_contents($pipes[2]);
          fclose($pipes[0]);  fclose($pipes[1]);  fclose($pipes[2]);
          // It is important that you close any pipes before calling proc_close in order to avoid a deadlock
          $return_value = proc_close($process);
          echo $return_value ;
          } */
    }

    public function danmu() {
        header('Content-type:text/json');
        $kros = M("danmu"); // 实例化模型类
        $condition['pid'] = array(
            'elt',
            1682000
        );
        $list = $kros->where($condition)->order('pid desc')->select();
        //print_r( $list );
        echo json_encode($list);
    }

    public function krosList() {
        $members[username] = $_SESSION['username'];
        $members[uid] = $_SESSION['uid'];
        $agent = $_SESSION['agent'];
        $title = $this->Api->get_title($_REQUEST[id]);
        $this->assign('title', $title);
        $portrait = $this->Api->get_portrait($_REQUEST[id]);
        $portrait = unserialize($portrait);
        $this->assign('portrait', $portrait[0]);
        $tempArr = $this->Api->get_members($_REQUEST[id]);
        $me_tempArr = $this->Api->get_members($members[uid]);
        $this->assign('gains', $tempArr['gains']);

        $category_id = $tempArr['category_id'];

        $categoryArr = $this->Api->get_category($category_id);



        $balance = (isset($me_tempArr['balance'])) ? $me_tempArr['balance'] : 0;
        $this->assign('balance', $balance);
        $this->assign('username', $tempArr['username']);
        $this->assign('nick_name', $tempArr['nicheng']);
        $this->assign('cate_name', $categoryArr['cate_name']);


        if (!empty($members)) {
            $this->assign('Example_username', $members[username]);
            $this->assign('Example_uid', $members[uid]);
            $uid = $members[uid];
            $identity = $this->Api->get_identity($uid, 2);
            $gag = $this->Api->get_gag($uid, 2);

            $this->assign('Example_identity', $identity);
            $this->assign('Example_gag', $gag);
            $this->assign('agent', $agent);
        } else {
            $Example_uid = $Example_username = '';
            $this->assign('Example_username', '游客');
        }
        $id = (isset($_REQUEST[id])) ? $_REQUEST[id] : 1;
        $this->assign('id', $id);
        $map["authorid"] = $id;
        $kros = M("thread"); // 实例化模型类
        import("@.ORG.Page"); //导入分页类
        $count = $kros->count(); //计算总数
        $p = new Page($count, 6);
        $list = $kros->limit($p->firstRow . ',' . $p->listRows)->order('tid desc')->where($map)->findAll();
        $_REQUEST[p] = (isset($_REQUEST[p])) ? $_REQUEST[p] : 1;
        foreach ($list as $key => $val) {

            $list[$key]['reply'] = get_reply($val['tid']);
            $list[$key]['p'] = $_REQUEST[p];

            $html = $val['subject1'];

            $preg = "/src=\"([\s\S]*?)\"/";

            preg_match_all($preg, $html, $arr);

//                return    print_r($arr);
            $list[$key]['img'] = $arr[1];
        }

//          return print_r($list);
        $kros1 = M("post"); // 实例化模型类
        $list1 = $kros->select();
        $p->setConfig('header', '篇记录');
        $p->setConfig('prev', "上一页");
        $p->setConfig('next', '下一页');
        $p->setConfig('first', '<<');
        $p->setConfig('last', '>>');
        $page = $p->show();
        $this->assign("page", $page);
        $this->assign("list", $list);
        $this->assign("list1", $list1);
        $this->display();
    }

    public function get_post() {
        $map["tid"] = $_REQUEST['tid'];
        import("@.ORG.Page"); //导入分页类
        $count = D("post")->count(); //计算总数
        $p = new Page($count, 6);
        $list = D("post")->where($map)->limit($p->firstRow . ',' . $p->listRows)->findAll();

        foreach ($list as $key => $val) {

            $list1[$key][author] = $val['author'];
            $list1[$key][message] = $val['message'];
        }
//     return  print_r($list1);
        echo json_encode($list1);
    }

    public function room() {
        $members[username] = $_SESSION['username'];
        $members[uid] = $_SESSION['uid'];
        $agent = $_SESSION['agent'];
        $title = $this->Api->get_title($_REQUEST[id]);
        $this->assign('title', $title);
        $portrait = $this->Api->get_portrait($_REQUEST[id]);
        $portrait = unserialize($portrait);
        $this->assign('portrait', $portrait[0]);

        if (!empty($members)) {
            $this->assign('Example_username', $members[username]);
            $this->assign('Example_uid', $members[uid]);
            $uid = $members[uid];
            $identity = $this->Api->get_identity($uid, 2);
            $gag = $this->Api->get_gag($uid, 2);

            $this->assign('Example_identity', $identity);
            $this->assign('Example_gag', $gag);
            $this->assign('agent', $agent);
        } else {
            $Example_uid = $Example_username = '';
            $this->assign('Example_username', '游客');
        }
        $id = (isset($_REQUEST[id])) ? $_REQUEST[id] : 1;
        $this->assign('id', $id);
        $this->display();
    }

    public function tables() {
        $this->display();
    }

    public function krosPostBiangList() {
        $members[username] = $_SESSION['username'];
        $members[uid] = $_SESSION['uid'];
        if (!empty($members)) {
            $this->assign('Example_username', $members[username]);
            $this->assign('Example_uid', $members[uid]);
        } else {
            $Example_uid = $Example_username = '';
            $this->assign('Example_username', '游客');
        }
        $this->display();
    }

    public function category() {
        $members[username] = $_SESSION['username'];
        $members[uid] = $_SESSION['uid'];
        if (!empty($members)) {
            $this->assign('Example_username', $members[username]);
            $this->assign('Example_uid', $members[uid]);
        } else {
            $Example_uid = $Example_username = '';
            $this->assign('Example_username', '游客');
        }
        $this->display();
    }

    public function krosListJsonForkrosPostBiangList() {
        $tag = (isset($_REQUEST[tag])) ? $_REQUEST[tag] : '英雄联盟';
        header('Content-type:text/json');
        $kros = M("gequ"); // 实例化模型类
        //  $condition['pid'] = array( 'elt' ,1682000);
        $list = $kros->query("select distinct (tag) from z_gequ");
        //$list=current($list);
        //$list=array_unique($list);
        $res['left'] = $list;
        $condition['tag'] = $tag;
        $rightList = $kros->join('z_members ON z_gequ.uid = z_members.uid')->where($condition)->order('id desc')->limit(50)->select(); // 创建数据对象
        $res['right'] = $rightList;
        /*       print_r($rightList);


          $this->display();


          die(); */
        echo json_encode($res);
    }

    public function renwu() {
        $kros = M("renwu");
        $data['renwu'] = $_REQUEST['renwu'];
        $kros->add($data);
    }

    public function q_renwu() {
        $kros = M("renwu");
        $list = $kros->where("1=1")->order('id')->findAll();
        $res = $list;
        echo json_encode($res);
    }

    public function d_renwu() {
        $map[renwu] = $_REQUEST['renwu'];
        $res = M('renwu')->where($map)->delete();
    }

    public function krosCategory() {
        $tag = (isset($_REQUEST[tag])) ? $_REQUEST[tag] : '英雄联盟';
        header('Content-type:text/json');
        $kros = M("category"); // 实例化模型类
        //  $condition['pid'] = array( 'elt' ,1682000);
        $list = $kros->where(array('cate_id'=>'15'))->order('sort_order')->findAll();
        //$list=current($list);
        //$list=array_unique($list);
        $res = $list;

        /*       print_r($rightList);


          $this->display();


          die(); */
        echo json_encode($res);
    }

     //krosCategoryList备份
      public function krosCategoryList() {

      header('Access-Control-Allow-Origin:*');
      $category_id = (isset($_REQUEST[Category_id])) ? $_REQUEST[Category_id] : 15;
      $p= (isset($_REQUEST[p])) ? $_REQUEST[p] : 1;
      header('Content-type:text/json');
      $kros = M("members"); // 实例化模型类
      $condition['category_id'] = $category_id;
      $condition['closed']=0;
      import("@.ORG.Page"); //导入分页类
      $count =$kros->join('z_category ON z_members.category_id = z_category.cate_id ')->where($condition)->count(); //计算总数
      $p = new Page($count, 50);
      $list = $kros->join('z_category ON z_members.category_id = z_category.cate_id ')->field('uid,fullscreenmode,rtmp_url,nicheng,title,biax,isv,huax,tk')->where($condition)->order('sort')->limit($p->firstRow . ',' . $p->listRows)->select();
      //$list=current($list);
      //$list=array_unique($list);

      foreach ($list as $key => $val) {
        $portrait = unserialize($val[portrait]);
        $portrait = $portrait[0];
        $list[$key]['portrait'] = $portrait;

        $kros_key="woqumima";
        $kros_url=$val['huax'].'?token='.$val['tk'];
        $list[$key]['nicheng']=$this->cryptoJsAesEncrypt($kros_key,$val['nicheng']);
        $list[$key]['rtmp_url']=$this->cryptoJsAesEncrypt($kros_key,$val['rtmp_url']);
        $list[$key]['biax']=$this->cryptoJsAesEncrypt($kros_key,$val['biax']);
        $list[$key]['huax']=$this->cryptoJsAesEncrypt($kros_key,$kros_url);

      }

      $res = $list;
      echo json_encode($res);
      }
     

    public function krosCategoryList2() {
        $redis = new Redis();
        $redis->connect('115.28.161.7', 6379);
        $redis->auth("Cjg13241064679"); 
        $res = unserialize($redis->get("tutorial-name"));
        echo json_encode($res);
    }

    public function krosCategoryList1() {

        header('Access-Control-Allow-Origin:*');
        $category_id = (isset($_REQUEST[Category_id])) ? $_REQUEST[Category_id] : 15;
        $p = (isset($_REQUEST[p])) ? $_REQUEST[p] : 1;
        header('Content-type:text/json');
        $kros = M("members"); // 实例化模型类
        $condition['category_id'] = $category_id;
        $condition['closed'] = 0;
        import("@.ORG.Page"); //导入分页类
        $count = $kros->join('z_category ON z_members.category_id = z_category.cate_id ')->where($condition)->count(); //计算总数
        $p = new Page($count, 12);
        $list = $kros->join('z_category ON z_members.category_id = z_category.cate_id ')->where($condition)->limit($p->firstRow . ',' . $p->listRows)->select();
        //$list=current($list);
        //$list=array_unique($list);

        foreach ($list as $key => $val) {
            $portrait = unserialize($val[portrait]);
            $portrait = $portrait[0];
            $list[$key]['portrait'] = $portrait;
        }

        $redis = new Redis();
        $redis->connect('115.28.161.7', 6379);
        $redis->auth("Cjg13241064679");
        $redis->set("tutorial-name", serialize($list));
        print_r($redis->get("tutorial-name"));
        //echo json_encode($res);
    }

    public function krosCategoryListCount() {
        $kros = M("members");
        $category_id = (isset($_REQUEST[category_id])) ? $_REQUEST[category_id] : 15;
        $condition['category_id'] = $category_id;
        $condition['closed'] = 0;
        $count = $kros->join('z_category ON z_members.category_id = z_category.cate_id ')->where($condition)->count();
        $res[count] = $count;
        echo json_encode($res);
    }
    
    //手机端显示
    public function recommend() {
        $kros = M("members"); // 实例化模型类
        $condition['review'] = 2;
        $condition['is_mobile'] = 1;
        //$list=$kros->order('uid')->findAll();

        $list = $kros->join('z_category ON z_members.category_id = z_category.cate_id ')->field('uid,fullscreenmode,rtmp_url,nicheng,title,biax,isv,huax,tk')->where($condition)->order('sort')->select();
        //$list=current($list);
        //$list=array_unique($list);
        foreach ($list as $key => $value) {

            $kros="woqumima";
            $kros_url=$value['huax'].'?token='.$value['tk'];
            $zhi=$value['nicheng'];
            $list[$key]['nicheng']=$this->cryptoJsAesEncrypt($kros,$zhi);
            $list[$key]['rtmp_url']=$this->cryptoJsAesEncrypt($kros,"abc");
            $list[$key]['biax']=$this->cryptoJsAesEncrypt($kros,$value['biax']);
            $list[$key]['huax']=$this->cryptoJsAesEncrypt($kros,$kros_url);
           
        }
        $res = $list;
        echo json_encode($res);
    }

    public function robot() {
        $members[username] = $_SESSION['username'];
        $members[uid] = $_SESSION['uid'];
        if (!empty($members)) {
            $this->assign('Example_username', $members[username]);
            $this->assign('Example_uid', $members[uid]);
        } else {
            $Example_uid = $Example_username = '';
        }
        $this->display();
    }

    public function charts() {
        $type = $_REQUEST['type'];
        $to_id = $_REQUEST['to_id'];
        $chartsId = $_REQUEST['chartsId'];
        $Model = new Model();
        $gift_log = $Model->query("SELECT z_gift_log.id,z_gift_log.to_id,z_gift_log.gift_id,z_gift_log.give_time,z_gift_log.type,sum(z_gift_log.worth) as sum,z_gift_log.uid FROM z_gift_log WHERE z_gift_log.to_id={$to_id} group by z_gift_log.uid ORDER BY sum desc");
        if ($type == 0) {
            $con_uid = $gift_log[$chartsId - 1][uid];
            $members = $this->Api->get_members($con_uid);
            $nicheng = $members[nicheng];
            $grade_level = $members[grade_level];
            $portrait = $this->Api->get_portrait($con_uid);
            $portrait = unserialize($portrait);
            $portrait = $portrait[0];
            $data = array(
                'nicheng' => $nicheng,
                'grade_level' => $grade_level,
                'portrait' => $portrait,
                'uid' => $con_uid,
            );
            echo json_encode($data);
        } elseif ($type == 1) {
            $gift_log = $Model->query("SELECT z_gift_log.id,z_gift_log.to_id,z_gift_log.gift_id,z_gift_log.give_time,z_gift_log.type,Sum(z_gift_log.worth)AS sum,z_gift_log.uid,z_members.username,z_members.nicheng,z_members.portrait,z_members.grade_level FROM z_gift_log INNER JOIN z_members ON z_members.uid=z_gift_log.uid WHERE z_gift_log.to_id={$to_id} group by z_gift_log.uid ORDER BY sum DESC");
            $arr = array();
            for ($i = 3; $i < 10; $i++) {
                if ($gift_log[$i]) {
                    array_push($arr, $gift_log[$i]);
                }
            }
            foreach ($arr as $key => $val) {
                $arr[$key]['chartsId'] = $key + 4;
            }
            // print_r($arr);            exit();
            echo json_encode($arr);
        } else {
            $gift_log = $Model->query("SELECT z_gift_log.id,z_gift_log.to_id,z_gift_log.gift_id,z_gift_log.give_time,z_gift_log.type,Sum(z_gift_log.worth)AS sum,z_gift_log.uid,z_members.username,z_members.nicheng,z_members.portrait,z_members.grade_level FROM z_gift_log INNER JOIN z_members ON z_members.uid=z_gift_log.uid WHERE z_gift_log.to_id={$to_id} group by z_gift_log.uid ORDER BY sum DESC");
            $arr = array();
            for ($i = 0; $i < 10; $i++) {
                if ($gift_log[$i]) {
                    array_push($arr, $gift_log[$i]);
                }
            }
            foreach ($arr as $key => $val) {
                $arr[$key]['chartsId'] = $key + 1;

                $portrait = $this->Api->get_portrait($arr[$key][uid]);
                $portrait = unserialize($portrait);
                $portrait = $portrait[0];

                $arr[$key]['portrait'] = $portrait;
            }
            // print_r($arr);            exit();
            echo json_encode($arr);
        }
    }

    public function follow_act() {
        $uid = $_REQUEST[uid];
        $item_id = $_REQUEST[item_id];
        $data = array(
            'uid' => $_REQUEST[uid],
            'item_id' => $_REQUEST[item_id],
            'type' => 'room',
            'add_time' => time(),
        );
        $info = M('collect')->add($data);
        $collect_sum = $this->Api->get_collect_sum($item_id);
        $info ? $this->Api->successres("操作成功!", $collect_sum) : $this->Api->faileres("操作失败!", $collect_sum);
    }

    public function follow_act_cancel() {
        $uid = $_REQUEST[uid];
        $item_id = $_REQUEST[item_id];

        $map = array(
            'uid' => $uid,
            'item_id' => $item_id,
        );
        $res = M('collect')->where($map)->delete();
        $collect_sum = $this->Api->get_collect_sum($item_id);
        $res ? $this->Api->successres("操作成功!", $collect_sum) : $this->Api->faileres("操作失败!", $collect_sum);
    }

    public function follow_query() {
        $uid = $_REQUEST[uid];
        $item_id = $_REQUEST[item_id];
        $map["uid"] = $uid;
        $map["item_id"] = $item_id;
        $res = M("collect")->where($map)->find();
        $collect_sum = $this->Api->get_collect_sum($item_id);
        $res ? $this->Api->successres("操作成功!", $collect_sum) : $this->Api->faileres("操作失败!", $collect_sum);
    }

    public function is_identity() {

        $from_client_name = $_REQUEST[from_client_name];
        $arr = $this->Api->get_members_($from_client_name);
        $uid = $arr[uid];
        $item_id = $_REQUEST[item_id];
        $map["uid"] = $uid;
        $map["item_id"] = $item_id;
        $map["is_manager"] = 1;
        $res = M("collect")->where($map)->find();


        $res ? $this->Api->successres("操作成功!") : $this->Api->faileres("操作失败!");
    }

    public function search() {
        $key_word = (isset($_REQUEST['key_word'])) ? $_REQUEST['key_word'] : $_POST['key_word'];

        $members = D('Members');
        $r = $members->search($key_word);
        $this->assign('search_arr', $r);
        $cage_arr = D('Category')->select();
        //return print_r($cage_arr);
        if ($this->json != 0) {
            $r ? $this->Api->successres("操作成功", $r) : $this->Api->faileres("操作失败!");
        } else {
            $this->assign('cate_arr', $cage_arr);
            $this->assign('count', count($r));
            $this->display();
        }
    }

    public function get_card() {
        $uid = $_REQUEST[uid];
        $tempArr = $this->Api->get_members($uid);

        $item_id = $_REQUEST[item_id];
        $be_username = $_REQUEST[username];
        $me = $this->Api->is_identity_with_username($be_username, $item_id);

        $arr = $this->Api->get_members_($be_username);
        $be_uid = $arr[uid];
        if ($uid == $item_id) {
            $res = 2; //是主播
        } elseif ($me == 1) {

            $res = 3; //对方是房管
        } else {
            $res = $this->Api->is_identity_do($uid, $item_id); //自己是房管
        }
        $is_gag = $this->Api->get_gag_with_username($be_username, $item_id); //对方是否被禁言

        $username = $_REQUEST[username];
        $ret = $this->Api->get_members_($username);
        $ret[role] = $res;
        $ret[is_gag] = $is_gag;
        $ret[act_username] = $tempArr[username];
        $ret['host'] = ($be_uid == $item_id) ? 1 : 0;
        $ret['is_manager'] = $me;
        echo json_encode($ret);
    }

    public function get_level($username) {
        $username = $_REQUEST[username];
        $arr = $this->Api->get_members_($username);
        $grade_level = $arr[grade_level];

        $data = array(
            'grade_level' => $grade_level,
        );

        echo json_encode($data);
    }

    public function gag_act() {
        $uid = $_REQUEST[uid];
        $item_id = $_REQUEST[item_id];
        $data = array(
            'uid' => $_REQUEST['uid'],
            'item_id' => $_REQUEST['item_id'],
            'type' => 'room',
            'add_time' => time(),
        );
        $info = M('gag')->add($data);
        $info ? $this->Api->successres() : $this->Api->faileres("操作失败!");
    }

    public function gag_act_cancel() {
        $uid = $_REQUEST[uid];
        $item_id = $_REQUEST[item_id];
        $map = array(
            'uid' => $uid,
            'item_id' => $item_id,
        );
        $res = M('gag')->where($map)->delete();
        $res ? $this->Api->successres() : $this->Api->faileres("操作失败!");
    }

    public function appointment_management_act() {
        $uid = $_REQUEST[uid];
        $item_id = $_REQUEST[item_id];
        $is_follow = $this->Api->is_follow($uid, $item_id);
        $map = array(
            'uid' => $_REQUEST['uid'],
            'item_id' => $_REQUEST['item_id'],
        );
        $data = array(
            'is_manager' => 1,
        );
        $res = M('collect')->where($map)->save($data);
        $res ? $this->Api->successres("操作成功", $is_follow) : $this->Api->faileres("操作失败!", $is_follow);
    }

    public function appointment_management_act_cancel() {

        $uid = $_REQUEST[uid];
        $item_id = $_REQUEST[item_id];
        $map = array(
            'uid' => $_REQUEST['uid'],
            'item_id' => $_REQUEST['item_id'],
        );
        $data = array(
            'is_manager' => 0,
        );
        $res = M('collect')->where($map)->save($data);
        $res ? $this->Api->successres() : $this->Api->faileres("操作失败!");
    }

    public function giveGift() {
        $uid = $_REQUEST['uid'];
        $gift_id = $_REQUEST['gift_id'];
        $members = $this->Api->get_members($uid);
        $toMembers = $this->Api->get_members($_REQUEST['to_id']);

        $balance = $members['balance'];
        $grade_score = $members['grade_score'];
        $gift = $this->Api->get_gift($gift_id);
        $price = $gift['price'];
        $score = $gift['score'];

        if ($balance < $price) {
            $this->Api->faileres("余额不足!");
        } else {
            $toData['gains'] = $toMembers['gains'] + $price;
            $toMap['uid'] = $_REQUEST['to_id'];
            $toRes = M('members')->where($toMap)->save($toData);
            $data['balance'] = $balance - $price;
            $data['grade_score'] = $grade_score + $score;
            $data['grade_level'] = $this->Api->get_level($data['grade_score']);
            $map['uid'] = $uid;
            $res = M('members')->where($map)->save($data);
            $data = array(
                'uid' => $_REQUEST['uid'],
                'to_id' => $_REQUEST['to_id'],
                'gift_id' => $_REQUEST['gift_id'],
                'quantity' => 1,
                'worth' => $price,
                'give_time' => time(),
            );
            $info = M('gift_log')->add($data);
            ($info && $res) ? $this->Api->successres() : $this->Api->faileres("操作失败!");
        }
    }

    function get_about_us() {

        $about_us = C('ABOUT_US');

        $about_us ? $this->Api->successres("操作成功", $about_us) : $this->Api->faileres("操作失败!");
    }

    public function krosList_json() {
        $members[username] = $_SESSION['username'];
        $members[uid] = $_SESSION['uid'];
        $title = $this->Api->get_title($_REQUEST[id]);
        $this->assign('title', $title);
        $portrait = $this->Api->get_portrait($_REQUEST[id]);
        $portrait = unserialize($portrait);
        $this->assign('portrait', $portrait[0]);
        $tempArr = $this->Api->get_members($_REQUEST[id]);
        $me_tempArr = $this->Api->get_members($members[uid]);
        $this->assign('gains', $tempArr['gains']);

        $category_id = $tempArr['category_id'];

        $categoryArr = $this->Api->get_category($category_id);
        $balance = (isset($me_tempArr['balance'])) ? $me_tempArr['balance'] : 0;
        $this->assign('balance', $balance);
        $this->assign('username', $tempArr['username']);
        $this->assign('nick_name', $tempArr['nicheng']);
        $this->assign('cate_name', $categoryArr['cate_name']);
        $collect_sum = $this->Api->get_collect_sum($_REQUEST[id]);

        $data = array(
            'id' => $_REQUEST['id'],
            'title' => $title,
            'portrait' => $portrait[0],
            'gains' => $tempArr['gains'],
            'balance' => $balance,
            'username' => $tempArr['username'],
            'cate_name' => $categoryArr['cate_name'],
            'collect_sum' => $collect_sum,
        );

        echo json_encode($data);
    }

    public function get_king_recommend() {

        header('Access-Control-Allow-Origin:*');
        $category_id = (isset($_REQUEST[Category_id])) ? $_REQUEST[Category_id] : 18;
        header('Content-type:text/json');
        $kros = M("members"); // 实例化模型类
        $condition['category_id'] = $category_id;

        $list = $kros->join('z_category ON z_members.category_id = z_category.cate_id ')->where($condition)->select();

        foreach ($list as $key => $val) {
            $portrait = unserialize($val[portrait]);
            $portrait = $portrait[0];
            $list[$key]['portrait'] = $portrait;
        }

        $res = $list;
        echo json_encode($res);
    }

    function test() {
        echo '1';
        $post = D('Postr');
//print_r($post);
//exit();
        $post->title = 'test title' . time();
        $post->description = 'test description';
        $post->created = time();
        $post->status = 1;

        $post->save();

        print_r($post->values());
    }

    function test1() {
        error_reporting(E_ALL);
        $path = 'Extend/Classes/';
        set_include_path(get_include_path() . PATH_SEPARATOR . $path);

        echo 1;

        require_once 'PHPLinq/LinqToObjects.php';
        $names = array("John", "Peter", "Joe", "Patrick", "Donald", "Eric");

        $result = from('$name')->in($names)
                ->where('$name => strlen($name) < 5')
                ->select('$name');

        print_r($result);
    }

    public function krosCategoryListRedis() {
        error_reporting(E_ALL);
        $category_id = (isset($_REQUEST[Category_id])) ? $_REQUEST[Category_id] : 15;
        $path = 'Extend/Classes/';
        set_include_path(get_include_path() . PATH_SEPARATOR . $path);
        require_once 'PHPLinq/LinqToObjects.php';
//        $categorys = null;
//        $members = null;
//        require_once('categorys.php');
//        require_once('members.php');
        $redis = new Redis();
        $redis->connect('115.28.161.7', 6379);
        $redis->auth("Cjg13241064679");
        $members = unserialize($redis->get("z_members"));
        foreach ($members as $key => $val) {

            $members[$key] = (object) $val;
        }
        $categorys = unserialize($redis->get("z_category"));
        foreach ($categorys as $key => $val) {

            $categorys[$key] = (object) $val;
        }

//print_r($categorys);
//exit();
        $result = from('$member')->in($members)
                ->join('$category')->in($categorys)->on('$member, $category => $member->category_id == $category->cate_id')
                ->where('$member => $member->category_id =='.$category_id.' && $member->closed ==0')
                ->select('$member = null,  $category = null => new {
							"cate_id" =>$category->cate_id,
							"username" => $member->username,
                                                        "reviewed" => $member->reviewed,
                                                        "uid" => $member->uid,
							"cate_name" => $category->cate_name,
							"portrait" => $member->portrait,
                                                        "nicheng" => $member->nicheng,
                                                        "title" => $member->title,
					  }');

       
        
       $list= json_decode(json_encode($result),TRUE);
         
        foreach ($list as $key => $val) {
      $portrait = unserialize($val[portrait]);
      $portrait = $portrait[0];
      $list[$key]['portrait'] = $portrait;

      }
//      print_r($list);
         echo json_encode($list);
        
    }

    function data2redis_members() {
        $kros = M("members"); // 实例化模型类
        $list = $kros->select();

        $redis = new Redis();
        $redis->connect('115.28.161.7', 6379);
        $redis->auth("Cjg13241064679");
        $redis->set("z_members", serialize($list),999*10000);
        print_r($redis->get("z_members"));
    }

    function data2redis_category() {
        $kros = M("category"); // 实例化模型类
        $list = $kros->select();

        $redis = new Redis();
        $redis->connect('115.28.161.7', 6379);
        $redis->auth("Cjg13241064679");
        $redis->set("z_category", serialize($list),999*10000);
        print_r($redis->get("z_category"));
    }
    
     function data2redis_danmu() {
        $kros = M("danmu"); // 实例化模型类
        $map["room_id"] = 71017;
        $list = $kros->where($map)->select();
        $redis = new Redis();
        $redis->connect('115.28.161.7', 6379);
        $redis->auth("Cjg13241064679");
        $redis->set("z_danmu", serialize($list),999*10000);
        print_r($redis->get("z_danmu"));
    }
    
    function get_danmu(){
        $redis = new Redis();
        $redis->connect('115.28.161.7', 6379);
        $redis->auth("Cjg13241064679");
        // $data = unserialize($redis->get("z_danmu288016"));
         $data = unserialize($redis->get("z_danmu"));
        echo json_encode($data);
    }

    function data2redis_danmu_nicheng() {
        $kros = M("post"); // 实例化模型类
        $map["room_id"] = 71017;
        $list = $kros->field('author')->distinct(true)->select();
        $list=$this->_array_column($list,'author');
        $redis = new Redis();
        $redis->connect('115.28.161.7', 6379);
        $redis->auth("Cjg13241064679");
        $redis->set("z_nicheng", serialize($list),999*10000);
        print_r($redis->get("z_nicheng"));
    }
    
    function get_danmu_nicheng(){
        //header('Content-type:text/json');
        $redis = new Redis();
        $redis->connect('115.28.161.7', 6379);
        $redis->auth("Cjg13241064679");
        // $data = unserialize($redis->get("z_danmu288016"));
         $data = unserialize($redis->get("z_nicheng"));
        $data=json_encode($data,JSON_UNESCAPED_UNICODE);
       $this->assign("data", $data);
        $this->display("nicheng");



    }

    public function get_vi($uid) {
        $uid = $_REQUEST[uid];
        $arr = $this->Api->get_members($uid);
        $vip = $arr[vip];
        $rt = $arr[rtmp_url];
        $kros_key="woqumima";
        $data = array(
            'vi' => $vip,
             'rt'=>$this->cryptoJsAesEncrypt($kros_key,$rt)
        );


        echo json_encode($data);

    }
    

        public function get_version($id) {
        $id = $_REQUEST[id];
        $arr = $this->Api->get_version($id);
        $is_update = $arr[is_update];
        $data = array(
            'is_update' => $is_update,
        );


        echo json_encode($data);

    }
        function content_height(){
            $content_height =M("setting")->where(array('name' =>'content_height'))->getField('data');
            $this->Api->successres("操作成功!", $content_height);
    }
    

         function is_login(){
        $members[username] = $_SESSION['username'];
        $members[uid] = $_SESSION['uid'];
        //print_r($user);exit();
        if (!empty($members)) {
                  $Example_uid =$members[uid];      
        } else {
            $Example_uid =0;
        }
            $this->Api->successres("操作成功!", $Example_uid);
    }
    
      public function robot1() {
        $members[username] = $_SESSION['username'];
        $members[uid] = $_SESSION['uid'];
        $agent = $_SESSION['agent'];
        $title = $this->Api->get_title($_REQUEST[id]);
        $this->assign('title', $title);
        $portrait = $this->Api->get_portrait($_REQUEST[id]);
        $portrait = unserialize($portrait);
        $this->assign('portrait', $portrait[0]);
        $tempArr = $this->Api->get_members($_REQUEST[id]);
        $me_tempArr = $this->Api->get_members($members[uid]);
        $this->assign('gains', $tempArr['gains']);

        $category_id = $tempArr['category_id'];

        $categoryArr = $this->Api->get_category($category_id);



        $balance = (isset($me_tempArr['balance'])) ? $me_tempArr['balance'] : 0;
        $this->assign('balance', $balance);
        $this->assign('username', $tempArr['username']);
        $this->assign('nick_name', $tempArr['nicheng']);
        $this->assign('cate_name', $categoryArr['cate_name']);


        if (!empty($members)) {
            $this->assign('Example_username', $members[username]);
            $this->assign('Example_uid', $members[uid]);
            $uid = $members[uid];
            $identity = $this->Api->get_identity($uid, 2);
            $gag = $this->Api->get_gag($uid, 2);

            $this->assign('Example_identity', $identity);
            $this->assign('Example_gag', $gag);
            $this->assign('agent', $agent);
        } else {
            $Example_uid = $Example_username = '';
            $this->assign('Example_username', '游客');
        }
        $id = (isset($_REQUEST[id])) ? $_REQUEST[id] : 1;
        $this->assign('id', $id);
        $map["authorid"] = $id;
        $kros = M("thread"); // 实例化模型类
        import("@.ORG.Page"); //导入分页类
        $count = $kros->count(); //计算总数
        $p = new Page($count, 6);
        $list = $kros->limit($p->firstRow . ',' . $p->listRows)->order('tid desc')->where($map)->findAll();
        $_REQUEST[p] = (isset($_REQUEST[p])) ? $_REQUEST[p] : 1;
        foreach ($list as $key => $val) {

            $list[$key]['reply'] = get_reply($val['tid']);
            $list[$key]['p'] = $_REQUEST[p];

            $html = $val['subject1'];

            $preg = "/src=\"([\s\S]*?)\"/";

            preg_match_all($preg, $html, $arr);

//                return    print_r($arr);
            $list[$key]['img'] = $arr[1];
        }

//          return print_r($list);
        $kros1 = M("post"); // 实例化模型类
        $list1 = $kros->select();
        $p->setConfig('header', '篇记录');
        $p->setConfig('prev', "上一页");
        $p->setConfig('next', '下一页');
        $p->setConfig('first', '<<');
        $p->setConfig('last', '>>');
        $page = $p->show();
        $this->assign("page", $page);
        $this->assign("list", $list);
        $this->assign("list1", $list1);
        $this->display();
    }
    
     protected function _array_column($input, $columnKey, $indexKey = NULL) {
        $columnKeyIsNumber = (is_numeric($columnKey)) ? TRUE : FALSE;
        $indexKeyIsNull = (is_null($indexKey)) ? TRUE : FALSE;
        $indexKeyIsNumber = (is_numeric($indexKey)) ? TRUE : FALSE;
        $result = array();

        foreach ((array) $input AS $key => $row) {
            if ($columnKeyIsNumber) {
                $tmp = array_slice($row, $columnKey, 1);
                $tmp = (is_array($tmp) && !empty($tmp)) ? current($tmp) : NULL;
            } else {
                $tmp = isset($row[$columnKey]) ? $row[$columnKey] : NULL;
            }
            if (!$indexKeyIsNull) {
                if ($indexKeyIsNumber) {
                    $key = array_slice($row, $indexKey, 1);
                    $key = (is_array($key) && !empty($key)) ? current($key) : NULL;
                    $key = is_null($key) ? 0 : $key;
                } else {
                    $key = isset($row[$indexKey]) ? $row[$indexKey] : 0;
                }
            }

            $result[$key] = $tmp;
        }

        return $result;
    }

    public function strencode($string) {
        $string = base64_encode($string);
        $key = md5('just a test');
        $len = strlen($key);
        $code = '';
        for ($i = 0; $i < strlen($string); $i++) {
            $k = $i % $len;
            $code .= $string [$i] ^ $key [$k];
        }
        return base64_encode($code);
    }



    /**
* Decrypt data from a CryptoJS json encoding string
*
* @param mixed $passphrase
* @param mixed $jsonString
* @return mixed
*/
function cryptoJsAesDecrypt($passphrase, $jsonString){
    $jsondata = json_decode($jsonString, true);
    try {
        $salt = hex2bin($jsondata["s"]);
        $iv  = hex2bin($jsondata["iv"]);
    } catch(Exception $e) { return null; }
    $ct = base64_decode($jsondata["ct"]);
    $concatedPassphrase = $passphrase.$salt;
    $md5 = array();
    $md5[0] = md5($concatedPassphrase, true);
    $result = $md5[0];
    for ($i = 1; $i < 3; $i++) {
        $md5[$i] = md5($md5[$i - 1].$concatedPassphrase, true);
        $result .= $md5[$i];
    }
    $key = substr($result, 0, 32);
    $data = openssl_decrypt($ct, 'aes-256-cbc', $key, true, $iv);
    return json_decode($data, true);
}

/**
* Encrypt value to a cryptojs compatiable json encoding string
*
* @param mixed $passphrase
* @param mixed $value
* @return string
*/
function cryptoJsAesEncrypt($passphrase, $value){
    $salt = openssl_random_pseudo_bytes(8);
    $salted = '';
    $dx = '';
    while (strlen($salted) < 48) {
        $dx = md5($dx.$passphrase.$salt, true);
        $salted .= $dx;
    }
    $key = substr($salted, 0, 32);
    $iv  = substr($salted, 32,16);
    $encrypted_data = openssl_encrypt(json_encode($value), 'aes-256-cbc', $key, true, $iv);
    $data = array("ct" => base64_encode($encrypted_data), "iv" => bin2hex($iv), "s" => bin2hex($salt));
    return json_encode($data);
}

}
